#include <stdio.h>
#include "ohos_init.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "cmsis_os2.h"

#define LED_GPIO1    7  // 第一个LED的GPIO引脚
#define LED_GPIO2    8  // 第二个LED的GPIO引脚

void ledGpioInit(int gpio_pin)
{
    // 初始化LED引脚
    int ret = IoTGpioInit(gpio_pin);
    if(ret != 0){
        printf("IoTGpioInit failed for GPIO%d :%#x \r\n", gpio_pin, ret);
        return;
    }
    /* 设置复用为GPIO功能 */
    ret = IoTGpioSetFunc(gpio_pin,IOT_GPIO_FUNC_GPIO_7_GPIO);
    if(ret != 0){
        printf("IoTGpioSetFunc failed for GPIO%d :%#x \r\n", gpio_pin, ret);
        return;
    }
    /* 设置方向为输出 */
    ret = IoTGpioSetDir(gpio_pin,IOT_GPIO_DIR_OUT);
    if(ret != 0){
        printf("IoTGpioSetDir failed for GPIO%d :%#x \r\n", gpio_pin, ret);
        return;
    }
    printf("----- LedGpioInit success for GPIO%d! -----\r\n", gpio_pin);
}

void Task1Func(void* argument)
{
    ledGpioInit(LED_GPIO1);
    if (IoTGpioSetOutputVal(LED_GPIO1, 1) != 1) {
        printf("Failed to set GPIO%d high\n", LED_GPIO1);
        return;
    }
    printf("Task1: LED GPIO%d is ON\n", LED_GPIO1);
}

void Task2Func(void* argument)
{
    ledGpioInit(LED_GPIO2);
    while(1){
        IoTGpioSetOutputVal(LED_GPIO2, 1);  // 点亮LED
        printf("Task2: LED GPIO%d is ON\n", LED_GPIO2);
        osDelay(500);  // 延时500毫秒

        IoTGpioSetOutputVal(LED_GPIO2, 0);  // 关闭LED
        printf("Task2: LED GPIO%d is OFF\n", LED_GPIO2);
        osDelay(500);  // 延时500毫秒
    }
}

void GPIO_outdemo()
{
    osThreadAttr_t attr;
    attr.name = "GPIO_Led1";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
    attr.priority = 25;

    osThreadId_t threadID1 = osThreadNew((osThreadFunc_t)Task1Func,NULL,&attr);
    if(threadID1 == NULL)
    {
        printf("Failed to create Task1!\r\n");
    }
    printf("Create Task1 OK!\r\n");

    attr.name = "GPIO_Led2";
    osThreadId_t threadID2 = osThreadNew((osThreadFunc_t)Task2Func,NULL,&attr);
    if(threadID2 == NULL)
    {
        printf("Failed to create Task2!\r\n");
    }
    printf("Create Task2 OK!\r\n");
}

APP_FEATURE_INIT(GPIO_outdemo);